/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.base.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.base.model.Organization;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.base.db.dao.OrganizationDao;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.util.tree.MyTreeNodeImpl;
import com.yunhoo.sys.util.tree.TreeRule;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.richfaces.event.TreeSelectionChangeEvent;
import org.richfaces.model.TreeNode;

@ManagedBean(name = "organizationBean")
@SessionScoped
public class OrganizationBean implements Serializable {

    private static DaoManager daom;
    private static OrganizationDao dao;
    private String[] rule = TreeRule.getOrganizationTreeRule();
    //
    private boolean addOrUpdate = false;
    private boolean editStatus = false;
    private TreeNode rootNode = null;
    private Organization org = null;

    {
        daom = DaoConfig.getDaoManager();
        dao = (OrganizationDao) daom.getDao(OrganizationDao.class);
    }

    public TreeNode getRootNode() {
        if (rootNode == null) {
            loadTree();
        }
        return rootNode;
    }

    private void loadTree() {
        rootNode = new MyTreeNodeImpl();
        List<Organization> li = null;
        try {
            li = dao.queryAll();
        } catch (SQLException ex) {
            Logger.getLogger(OrganizationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        TreeUtil.addNode(li, rootNode, rule);
    }

    public void selected(TreeSelectionChangeEvent event) {
        org = (Organization) TreeUtil.listener(event);
        initStatus();
    }

    public void add() {
        addOrUpdate = true;
        editStatus = true;
        org = new Organization(true);
    }

    public void update() {
        addOrUpdate = false;
        editStatus = true;
    }

    public void delete() {
        org.setSupCode(TreeUtil.parentCode(org.getCode(), rule));
        FacesContext context = FacesContext.getCurrentInstance();
        if (org.getIsEnd() == 0) {
            ToolKit.msgs_info(context, null, "非末级节点,不可删除!");
            return;
        }
        boolean ok = true;
        try {
            daom.startTransaction();
            List list = dao.directSubNodes(org);
            if (list != null && list.size() == 1) { //要删除节点,如果无兄弟节点,修改其父节点 isEnd属性为"1"
                Organization parentNode = new Organization();
                parentNode.setCode(org.getSupCode());
                parentNode.setIsEnd(1);
                dao.updateIsEnd(parentNode);
            }
            dao.delete(org);
            daom.commitTransaction();
        } catch (SQLException ex) {
            ok = false;
            daom.endTransaction();
            Logger.getLogger(OrganizationBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (ok) {
            org = null;
            loadTree();
            initStatus();
        }
    }

    public void checkSave() {
        boolean ok = save();
        if (ok) {
            initStatus();
            loadTree();
        }
    }

    private boolean save() {
        boolean ok = true;
        try {
            daom.startTransaction();
            org.setGrade(TreeUtil.codeGrade(org.getCode(), rule));
            org.setSupCode(TreeUtil.parentCode(org.getCode(), rule));
            //新增
            if (addOrUpdate) {
                org.setJl_RQ(new Date());
                org.setJlr_ID(LoginParam.getPer().getCpsn_number());
                FacesContext context = FacesContext.getCurrentInstance();
                if (addOrUpdate && !TreeUtil.checkCodeLegal(org.getCode(), rule)) {
                    ToolKit.msgs_info(context, null, "编码不符合规范!");
                    return false;
                }
                Organization codeRepeat = dao.queryById(org.getCode().trim());
                if (codeRepeat != null) {
                    ToolKit.msgs_info(context, null, "编码重复!");
                    return false;
                }
                Organization nameRepeat = dao.nameRepeatForInsert(org);
                if (nameRepeat != null) {
                    ToolKit.msgs_info(context, null, "名称重复!");
                    return false;
                }
                if (org.getGrade() == 1) {
                    //根节点
                    org.setIsEnd(1);
                    dao.insert(org);
                } else {
                    //非根节点
                    Organization parent = dao.queryById(org.getSupCode());
                    if (parent == null) {
                        ToolKit.msgs_info(context, null, "上级不存在!");
                        return false;
                    }
                    if (parent.getIsEnd() == 1) {//父节点IsEnd是1的改为0;
                        parent.setIsEnd(0);
                        dao.updateIsEnd(parent);
                    }
                    org.setIsEnd(1);
                    dao.insert(org);
                }
            }
            //修改
            if (!addOrUpdate) {
                org.setXg_RQ(new Date());
                org.setXgr_ID(LoginParam.getPer().getCpsn_number());
                Organization nameRepeat = dao.nameRepeatForUpdate(org);
                if (nameRepeat != null) {
                    ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "名称重复!");
                    return false;
                }
                dao.update(org);
            }
            daom.commitTransaction();
        } catch (SQLException ex) {
            ok = false;
            Logger.getLogger(CategoryBean.class.getName()).log(Level.SEVERE, null, ex);
            daom.endTransaction();
        }
        return ok;
    }

    public void checkSave_() {
        boolean ok = true;
        try {
            daom.startTransaction();
            save_();
            daom.commitTransaction();
        } catch (SQLException ex) {
            ok = false;
            daom.endTransaction();
            Logger.getLogger(CategoryBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (ok) {
            initStatus();
            loadTree();
        }
    }

    private void save_() throws SQLException {
        org.setGrade(TreeUtil.codeGrade(org.getCode(), rule));
        org.setSupCode(TreeUtil.parentCode(org.getCode(), rule));
        if (addOrUpdate) {
            org.setJl_RQ(new Date());
            org.setJlr_ID(LoginParam.getPer().getCpsn_number());
            FacesContext context = FacesContext.getCurrentInstance();
            if (addOrUpdate && !TreeUtil.checkCodeLegal(org.getCode(), rule)) {
                ToolKit.msgs_info(context, null, "编码不符合规范!");
                return;
            }
            Organization codeRepeat = dao.queryById(org.getCode().trim());
            if (codeRepeat != null) {
                ToolKit.msgs_info(context, null, "编码重复!");
                return;
            }
            Organization nameRepeat = dao.nameRepeatForInsert(org);
            if (nameRepeat != null) {
                ToolKit.msgs_info(context, null, "名称重复!");
                return;
            }
            if (org.getGrade() == 1) {
                //根节点
                org.setIsEnd(1);
                dao.insert(org);
            } else {
                //非根节点
                Organization parent = dao.queryById(org.getSupCode());
                if (parent == null) {
                    ToolKit.msgs_info(context, null, "上级不存在!");
                    return;
                }
                if (parent.getIsEnd() == 1) { //父节点IsEnd是1的改为0;
                    parent.setIsEnd(0);
                    dao.updateIsEnd(parent);
                }
                org.setIsEnd(1);
                dao.insert(org);
            }
        } else {
            org.setXg_RQ(new Date());
            org.setXgr_ID(LoginParam.getPer().getCpsn_number());
            Organization nameRepeat = dao.nameRepeatForUpdate(org);
            if (nameRepeat != null) {
                ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "名称重复!");
                return;
            }
            dao.update(org);
        }
    }

    public void cancel() {
        if (addOrUpdate) {
            org = null;
        }
        initStatus();
    }

    private void initStatus() {
        addOrUpdate = false;
        editStatus = false;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isEditStatus() {
        return editStatus;
    }

    public void setEditStatus(boolean editStatus) {
        this.editStatus = editStatus;
    }

    public Organization getOrg() {
        return org;
    }

    public void setOrg(Organization org) {
        this.org = org;
    }
}
